<!--
  排班时间段组件
-->
<template>
  <div>
    <el-time-picker
        is-range
        v-model="range"
        :editable="false"
        :clearable="false"
        range-separator="-"
        @change="change"
        :start-placeholder="$t('calling.startTime')"
        :end-placeholder="$t('calling.finishTime')"
        :placeholder="$t('calling.timeInterval')">
    </el-time-picker>
    <el-button
      type="text"
      icon="el-icon-minus"
      style="margin-left:16px"

      @click="$emit('delete')"
    ></el-button>
    <el-button
      type="text"
      icon="el-icon-plus"
      :disabled="!addable"
      @click="$emit('add')"
    ></el-button>
  </div>
</template>

<script>
import dayjs from 'dayjs'

const DATE_FORMAT = 'YYYY-MM-DD'
const TIME_FORMAT = 'HH:mm'
const FULLTIME_FORMAT = 'HH:mm:ss'
const DATE_FIELD_NAME = 'date'
const DAY_MAX_TIME = 24 * 60 * 60 * 1000
const DAY_MAX_TIME_LACK_SECOND = DAY_MAX_TIME - 1000

export default {
  name: 'ResourceScheduleGroupItem',
  // components: {},
  props: {
    minTime: {
      type: Number,
      default: 0
    },
    maxTime: {
      type: Number,
      default: DAY_MAX_TIME
    },
    value: {
      type: Object,
      default: () => ({
        start: 0,
        end: 0
      })
    },
    addable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      today: dayjs()
        .startOf('day')
        .valueOf(),
      range: []
    }
  },
  computed: {
    minTimeFormat() {
      return dayjs(this.minTime + this.today).format(FULLTIME_FORMAT)
    },
    maxTimeFormat() {
      return dayjs(this.maxTime + this.today).format(FULLTIME_FORMAT)
    },
    selectableRange() {
      return `${this.minTimeFormat} - ${this.maxTimeFormat}`
    }
  },
  watch: {
    // val格式:  [x1, x2] 其中 0<= x1 <= x2 <= 24*60*60*1000
    value(val) {
      this.range = this.valueToRange(val)
    }
  },
  async created() {
    this.range = this.valueToRange(this.value)
  },
  methods: {
    // val格式 [x1, x2] 其中 x1,x2 均为Date对象
    // rangeToValue
    change(val) {
      let [start, end] = val
      start = dayjs(start).valueOf() - this.today
      end = dayjs(end).valueOf() - this.today

      // 强制修正
      if (start < this.minTime) {
        start = this.minTime
      }
      if (end > this.maxTime) {
        end = this.maxTime
      }
      if (end >= DAY_MAX_TIME_LACK_SECOND) {
        end = DAY_MAX_TIME
      }
      this.$emit('input', {
        start,
        end
      })
    },
    valueToRange(val) {

      if (val.end >= DAY_MAX_TIME) {
        return [
          new Date(this.today + val.start),
          new Date(this.today + DAY_MAX_TIME_LACK_SECOND)
        ]
      }
      return [new Date(this.today + val.start), new Date(this.today + val.end)]
    }
  }
}
</script>

<style lang="css"></style>
